﻿using System;
using System.Threading;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace DwarfInterpreter
{
    class WhileToken : Token
    {
        const int REPEAT_INTERVAL = 750;

        private WhileToken nestedWhile = null;
        private DwarfToken command;
        private string condition;

        public WhileToken(string[] symbols)
        {
            condition = symbols[2];
            if (symbols.Length > 5)
            {
                nestedWhile = new WhileToken(GetNestingWhileSymbols(symbols));
            }
            else
            {
                command = new DwarfToken(symbols[4]);
            }
        }

        override public void Run(Dwarf dwarf) 
        { 
            bool trueCondition;
            while (trueCondition = DwarfWorld.Instance.GetState(condition))
            {
                if (nestedWhile == null)
                {
                    command.Run(dwarf);
                    Thread.Sleep(REPEAT_INTERVAL);
                }
                else
                {
                    // TODO: check nesting
                    nestedWhile.Run(dwarf);
                }
            }
        }

        public static bool IsWhileToken(string[] symbols)
        {
            bool isWhileCondition = (symbols[0].CompareTo("while") == 0)   &&
                                    (symbols[1].CompareTo("(") == 0)       &&
                                    StringUtils.IsSimpleString(symbols[2]) &&
                                    (symbols[3].CompareTo(")") == 0);

            bool isNested = symbols.Length > 5;

            if (isWhileCondition && isNested)
            {
                return IsWhileToken(GetNestingWhileSymbols(symbols));
            }

            return isWhileCondition && DwarfToken.IsDwarfCommand(symbols[4]);
        }

        private static string[] GetNestingWhileSymbols(string[] symbols)
        {
            List<string> sym = symbols.ToList();
            List<string> nestingWhile = sym.GetRange(4, sym.Count - 4);
            return nestingWhile.ToArray();
        }

    }
}
